import { useRef, useEffect, useState } from 'react';
import { useGameStore } from '../store/gameStore';
import { ChessUnitType, Position } from '../types/game';
import { ChessRules } from '../utils/chessRules';
import { MoodSystem } from '../systems/MoodSystem';

const CELL_SIZE = 50;
const BOARD_WIDTH = 10;
const BOARD_HEIGHT = 9;

export default function GameBoard() {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [hoveredCell, setHoveredCell] = useState<Position | null>(null);
  
  const {
    gameState,
    currentLevel,
    settings,
    deployUnit,
    selectUnit,
    removeUnit,
    collectMoodItem,
    getMoodItemAt,
    getVisualEffectsSystem,
    createVisualEffect
  } = useGameStore();

  // 获取鼠标在棋盘上的位置
  const getMousePosition = (event: React.MouseEvent<HTMLCanvasElement>): Position | null => {
    const canvas = canvasRef.current;
    if (!canvas) return null;

    const rect = canvas.getBoundingClientRect();
    const x = Math.floor((event.clientX - rect.left) / CELL_SIZE);
    const y = Math.floor((event.clientY - rect.top) / CELL_SIZE);

    if (x >= 0 && x < BOARD_WIDTH && y >= 0 && y < BOARD_HEIGHT) {
      return { x, y };
    }
    return null;
  };

  // 检查位置是否可以部署单位
  const canDeployAt = (position: Position): boolean => {
    if (!currentLevel || !gameState.selectedUnit) return false;
    
    // 使用象棋规则验证
    const validationResult = ChessRules.canDeployUnit(
      gameState.selectedUnit,
      position,
      gameState.units,
      currentLevel.boardLayout
    );
    
    if (!validationResult.canDeploy) {
      return false;
    }

    // 额外检查：不能在敌军路径上部署
    const onPath = currentLevel.enemyPath.some(
      pathPoint => pathPoint.x === position.x && pathPoint.y === position.y
    );
    if (onPath) return false;

    return true;
  };

  // 获取部署提示信息
  const getDeploymentHint = (position: Position): string | null => {
    if (!currentLevel || !gameState.selectedUnit) return null;
    
    const validationResult = ChessRules.canDeployUnit(
      gameState.selectedUnit,
      position,
      gameState.units,
      currentLevel.boardLayout
    );
    
    return validationResult.reason || null;
  };

  // 处理鼠标点击
  const handleCanvasClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
    const position = getMousePosition(event);
    if (!position) return;

    if (event.button === 0) { // 左键点击
      // 检查是否点击了意境物品
      const moodItem = getMoodItemAt(position);
      if (moodItem) {
        const result = collectMoodItem(position);
        if (result.success && result.message) {
          console.log(result.message);
        }
        return;
      }
      
      if (gameState.selectedUnit && canDeployAt(position)) {
        const success = deployUnit(gameState.selectedUnit, position);
        if (success) {
          // 部署成功后可以选择继续部署同类型单位或取消选择
          // 这里保持选中状态，方便连续部署
          // 创建部署视觉效果
          createVisualEffect('unitDeploy', position);
        }
      }
    } else if (event.button === 2) { // 右键点击
      // 检查是否点击了已有单位
      const clickedUnit = gameState.units.find(
        unit => unit.position.x === position.x && unit.position.y === position.y
      );
      if (clickedUnit) {
        // 这里可以实现升级或出售单位的逻辑
        console.log('Right clicked unit:', clickedUnit);
      }
    }
  };

  // 处理鼠标移动
  const handleMouseMove = (event: React.MouseEvent<HTMLCanvasElement>) => {
    const position = getMousePosition(event);
    setHoveredCell(position);
  };

  // 处理鼠标离开
  const handleMouseLeave = () => {
    setHoveredCell(null);
  };

  // 绘制棋盘
  const drawBoard = (ctx: CanvasRenderingContext2D) => {
    if (!currentLevel) return;

    // 清空画布
    ctx.clearRect(0, 0, BOARD_WIDTH * CELL_SIZE, BOARD_HEIGHT * CELL_SIZE);

    // 绘制棋盘背景
    for (let y = 0; y < BOARD_HEIGHT; y++) {
      for (let x = 0; x < BOARD_WIDTH; x++) {
        const isWalkable = currentLevel.boardLayout[y][x] === 1;
        
        // 设置格子颜色
        if (isWalkable) {
          ctx.fillStyle = '#f3e8d0'; // 可通行区域 - 米黄色
        } else {
          ctx.fillStyle = '#8b7355'; // 不可通行区域 - 棕色
        }
        
        ctx.fillRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
        
        // 绘制网格线（如果设置中启用）
        if (settings.showGrid) {
          ctx.strokeStyle = '#d4af37';
          ctx.lineWidth = 1;
          ctx.strokeRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
        }
      }
    }

    // 绘制敌军路径（如果设置中启用）
    if (settings.showPath && currentLevel.enemyPath.length > 0) {
      ctx.strokeStyle = '#ff6b6b';
      ctx.lineWidth = 3;
      ctx.lineCap = 'round';
      ctx.lineJoin = 'round';
      
      ctx.beginPath();
      const firstPoint = currentLevel.enemyPath[0];
      ctx.moveTo(
        firstPoint.x * CELL_SIZE + CELL_SIZE / 2,
        firstPoint.y * CELL_SIZE + CELL_SIZE / 2
      );
      
      for (let i = 1; i < currentLevel.enemyPath.length; i++) {
        const point = currentLevel.enemyPath[i];
        ctx.lineTo(
          point.x * CELL_SIZE + CELL_SIZE / 2,
          point.y * CELL_SIZE + CELL_SIZE / 2
        );
      }
      ctx.stroke();
      
      // 绘制路径点
      currentLevel.enemyPath.forEach((point, index) => {
        ctx.fillStyle = index === 0 ? '#4ade80' : index === currentLevel.enemyPath.length - 1 ? '#ef4444' : '#fbbf24';
        ctx.beginPath();
        ctx.arc(
          point.x * CELL_SIZE + CELL_SIZE / 2,
          point.y * CELL_SIZE + CELL_SIZE / 2,
          6,
          0,
          2 * Math.PI
        );
        ctx.fill();
      });
    }

    // 绘制悬停效果
    if (hoveredCell && gameState.selectedUnit) {
      const canDeploy = canDeployAt(hoveredCell);
      ctx.fillStyle = canDeploy ? 'rgba(34, 197, 94, 0.3)' : 'rgba(239, 68, 68, 0.3)';
      ctx.fillRect(
        hoveredCell.x * CELL_SIZE,
        hoveredCell.y * CELL_SIZE,
        CELL_SIZE,
        CELL_SIZE
      );
    }

    // 绘制可部署区域提示（当选中单位时）
    if (gameState.selectedUnit) {
      for (let y = 0; y < BOARD_HEIGHT; y++) {
        for (let x = 0; x < BOARD_WIDTH; x++) {
          if (canDeployAt({ x, y })) {
            ctx.fillStyle = 'rgba(34, 197, 94, 0.1)';
            ctx.fillRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
          }
        }
      }
    }
  };

  // 绘制单位
  const drawUnits = (ctx: CanvasRenderingContext2D) => {
    gameState.units.forEach(unit => {
      const x = unit.position.x * CELL_SIZE + CELL_SIZE / 2;
      const y = unit.position.y * CELL_SIZE + CELL_SIZE / 2;
      
      // 检查是否有攻击动画
      const isAttacking = unit.lastAttackTime && (Date.now() - unit.lastAttackTime) < 300;
      const attackScale = isAttacking ? 1.2 : 1;
      
      // 检查是否有buff效果
      const hasBuff = unit.buff && (Date.now() - unit.buff.startTime) < unit.buff.duration;
      
      ctx.save();
      ctx.translate(x, y);
      ctx.scale(attackScale, attackScale);
      
      // 绘制buff光环
      if (hasBuff) {
        const buffTime = Date.now() - unit.buff.startTime;
        const buffProgress = (buffTime % 1000) / 1000;
        const glowRadius = CELL_SIZE * 0.5 + Math.sin(buffProgress * Math.PI * 2) * 5;
        
        const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, glowRadius);
        gradient.addColorStop(0, '#fbbf2440');
        gradient.addColorStop(1, '#fbbf2400');
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(0, 0, glowRadius, 0, Math.PI * 2);
        ctx.fill();
      }
      
      // 绘制单位背景圆圈
      ctx.fillStyle = getUnitColor(unit.type);
      ctx.beginPath();
      ctx.arc(0, 0, CELL_SIZE / 3, 0, 2 * Math.PI);
      ctx.fill();
      
      // 绘制单位边框
      ctx.strokeStyle = isAttacking ? '#ffffff' : '#8b5a2b';
      ctx.lineWidth = isAttacking ? 3 : 2;
      ctx.stroke();
      
      // 绘制单位文字
      ctx.fillStyle = '#ffffff';
      ctx.font = 'bold 16px serif';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText(getUnitText(unit.type), 0, 0);
      
      ctx.restore();
      
      // 绘制等级指示器
      if (unit.level > 1) {
        ctx.fillStyle = '#ffd700';
        ctx.font = 'bold 10px sans-serif';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(
          unit.level.toString(),
          x + CELL_SIZE / 4,
          y - CELL_SIZE / 4
        );
      }
      
      // 绘制攻击线条
      if (isAttacking) {
        drawAttackEffect(ctx, unit, x, y);
      }
    });
  };

  // 绘制敌军
  const drawEnemies = (ctx: CanvasRenderingContext2D) => {
    gameState.enemies.forEach(enemy => {
      const x = enemy.position.x * CELL_SIZE + CELL_SIZE / 2;
      const y = enemy.position.y * CELL_SIZE + CELL_SIZE / 2;
      
      // 检查是否正在死亡
      const isDying = enemy.health <= 0;
      const deathTime = enemy.deathTime || 0;
      const deathProgress = isDying ? Math.min(1, (Date.now() - deathTime) / 500) : 0;
      
      if (isDying && deathProgress >= 1) {
        // 创建死亡效果
        createVisualEffect('enemyDeath', { x: enemy.position.x, y: enemy.position.y });
        return; // 不绘制已死亡的敌军
      }
      
      ctx.save();
      
      // 死亡动画效果
      if (isDying) {
        ctx.globalAlpha = 1 - deathProgress;
        ctx.translate(x, y);
        ctx.rotate(deathProgress * Math.PI * 2);
        ctx.scale(1 - deathProgress * 0.5, 1 - deathProgress * 0.5);
        ctx.translate(-x, -y);
      }
      
      // 受伤闪烁效果
      const isHurt = enemy.lastHitTime && (Date.now() - enemy.lastHitTime) < 200;
      if (isHurt) {
        ctx.globalAlpha = 0.7;
      }
      
      // 绘制敌军背景
      ctx.fillStyle = isHurt ? '#ffffff' : getEnemyColor(enemy.type);
      ctx.beginPath();
      ctx.arc(x, y, CELL_SIZE / 4, 0, 2 * Math.PI);
      ctx.fill();
      
      // 绘制敌军边框
      ctx.strokeStyle = '#7f1d1d';
      ctx.lineWidth = 2;
      ctx.stroke();
      
      // 绘制敌军符号
      ctx.fillStyle = '#ffffff';
      ctx.font = `bold ${CELL_SIZE * 0.2}px Arial`;
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText('敌', x, y);
      
      ctx.restore();
      
      // 绘制血量条（不受死亡动画影响）
      if (!isDying) {
        const healthPercent = enemy.health / enemy.maxHealth;
        const barWidth = CELL_SIZE * 0.8;
        const barHeight = 4;
        const barX = x - barWidth / 2;
        const barY = y - CELL_SIZE / 2 + 5;
        
        // 血量条背景
        ctx.fillStyle = '#7f1d1d';
        ctx.fillRect(barX, barY, barWidth, barHeight);
        
        // 血量条前景
        ctx.fillStyle = healthPercent > 0.5 ? '#22c55e' : healthPercent > 0.25 ? '#eab308' : '#ef4444';
        ctx.fillRect(barX, barY, barWidth * healthPercent, barHeight);
      }
    });
  };
  
  // 绘制攻击效果
  const drawAttackEffect = (ctx: CanvasRenderingContext2D, unit: any, unitX: number, unitY: number) => {
    // 寻找攻击目标
    const target = gameState.enemies.find(enemy => {
      const distance = Math.sqrt(
        Math.pow(enemy.position.x - unit.position.x, 2) + 
        Math.pow(enemy.position.y - unit.position.y, 2)
      );
      return distance <= unit.attackRange;
    });
    
    if (!target) return;
    
    const targetX = target.position.x * CELL_SIZE + CELL_SIZE / 2;
    const targetY = target.position.y * CELL_SIZE + CELL_SIZE / 2;
    
    // 绘制攻击线条
    ctx.save();
    ctx.strokeStyle = '#fbbf24';
    ctx.lineWidth = 3;
    ctx.lineCap = 'round';
    
    // 添加发光效果
    ctx.shadowColor = '#fbbf24';
    ctx.shadowBlur = 10;
    
    ctx.beginPath();
    ctx.moveTo(unitX, unitY);
    ctx.lineTo(targetX, targetY);
    ctx.stroke();
    
    // 绘制攻击粒子
    const particleCount = 5;
    for (let i = 0; i < particleCount; i++) {
      const progress = i / particleCount;
      const x = unitX + (targetX - unitX) * progress;
      const y = unitY + (targetY - unitY) * progress;
      
      ctx.fillStyle = '#fbbf24';
      ctx.beginPath();
      ctx.arc(x + (Math.random() - 0.5) * 10, y + (Math.random() - 0.5) * 10, 2, 0, Math.PI * 2);
      ctx.fill();
    }
    
    ctx.restore();
  };

  // 获取单位颜色
  const getUnitColor = (type: ChessUnitType): string => {
    const colors = {
      soldier: '#8b5a2b',    // 锐士 - 棕色
      cannon: '#dc2626',     // 神射 - 红色
      horse: '#059669',      // 骠骑 - 绿色
      chariot: '#7c3aed',    // 战车 - 紫色
      advisor: '#0891b2',    // 谋士 - 青色
      minister: '#ea580c',   // 丞相 - 橙色
      general: '#facc15'     // 元帅 - 金色
    };
    return colors[type];
  };

  // 获取单位文字
  const getUnitText = (type: ChessUnitType): string => {
    const texts = {
      soldier: '兵',
      cannon: '炮',
      horse: '马',
      chariot: '车',
      advisor: '士',
      minister: '相',
      general: '将'
    };
    return texts[type];
  };

  // 获取敌军颜色
  const getEnemyColor = (type: string): string => {
    const colors = {
      infantry: '#991b1b',
      cavalry: '#7c2d12',
      shieldBearer: '#374151',
      siegeEngine: '#1f2937',
      eliteGeneral: '#7c1d6f'
    };
    return colors[type as keyof typeof colors] || '#991b1b';
  };

  // 主绘制函数
  const draw = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    drawBoard(ctx);
    drawUnits(ctx);
    drawEnemies(ctx);
    
    // 绘制意境物品
    gameState.moodItems.forEach(moodItem => {
      drawMoodItem(ctx, moodItem);
    });
  };

  // 绘制意境物品
  const drawMoodItem = (ctx: CanvasRenderingContext2D, moodItem: any) => {
    if (moodItem.collected) return;
    
    const x = moodItem.position.x * CELL_SIZE + CELL_SIZE / 2;
    const y = moodItem.position.y * CELL_SIZE + CELL_SIZE / 2;
    const config = MoodSystem.getMoodConfig(moodItem.type);
    
    // 计算生命周期进度
    const elapsed = Date.now() - moodItem.createdTime;
    const lifeProgress = elapsed / moodItem.lifespan;
    const opacity = Math.max(0.3, 1 - lifeProgress * 0.7); // 随时间淡化
    
    // 绘制光晕效果
    const gradient = ctx.createRadialGradient(x, y, 0, x, y, CELL_SIZE * 0.6);
    gradient.addColorStop(0, `${config.color}40`); // 40% 透明度
    gradient.addColorStop(1, `${config.color}00`); // 完全透明
    
    ctx.fillStyle = gradient;
    ctx.beginPath();
    ctx.arc(x, y, CELL_SIZE * 0.6, 0, Math.PI * 2);
    ctx.fill();
    
    // 绘制主体
    ctx.globalAlpha = opacity;
    ctx.fillStyle = config.color;
    ctx.beginPath();
    ctx.arc(x, y, CELL_SIZE * 0.25, 0, Math.PI * 2);
    ctx.fill();
    
    // 绘制稀有度边框
    if (moodItem.rarity !== 'common') {
      ctx.strokeStyle = moodItem.rarity === 'epic' ? '#fbbf24' : '#8b5cf6';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.arc(x, y, CELL_SIZE * 0.3, 0, Math.PI * 2);
      ctx.stroke();
    }
    
    // 绘制符号
    ctx.globalAlpha = 1;
    ctx.fillStyle = '#ffffff';
    ctx.font = `${CELL_SIZE * 0.3}px Arial`;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(config.symbol, x, y);
    
    // 绘制价值提示
    ctx.fillStyle = '#374151';
    ctx.font = `${CELL_SIZE * 0.2}px Arial`;
    ctx.fillText(`+${moodItem.value}`, x, y + CELL_SIZE * 0.45);
    
    // 重置透明度
    ctx.globalAlpha = 1;
  };

  // 监听游戏状态变化并重绘
  useEffect(() => {
    draw();
    
    // 设置视觉效果系统的画布
    const visualEffectsSystem = getVisualEffectsSystem();
    if (visualEffectsSystem && canvasRef.current) {
      visualEffectsSystem.setCanvas(canvasRef.current);
    }
  }, [gameState, currentLevel, settings, hoveredCell, getVisualEffectsSystem]);

  return (
    <div className="flex items-center justify-center">
      <div className="relative border-4 border-amber-600 rounded-lg overflow-hidden shadow-lg">
        <canvas
          ref={canvasRef}
          width={BOARD_WIDTH * CELL_SIZE}
          height={BOARD_HEIGHT * CELL_SIZE}
          className="cursor-pointer bg-amber-50"
          onClick={handleCanvasClick}
          onMouseMove={handleMouseMove}
          onMouseLeave={handleMouseLeave}
          onContextMenu={(e) => e.preventDefault()} // 禁用右键菜单
        />
        
        {/* 棋盘坐标标识 */}
        <div className="absolute -top-6 left-0 right-0 flex justify-around text-xs text-amber-700 font-medium">
          {Array.from({ length: BOARD_WIDTH }, (_, i) => (
            <span key={i}>{i + 1}</span>
          ))}
        </div>
        <div className="absolute -left-6 top-0 bottom-0 flex flex-col justify-around text-xs text-amber-700 font-medium">
          {Array.from({ length: BOARD_HEIGHT }, (_, i) => (
            <span key={i}>{String.fromCharCode(65 + i)}</span>
          ))}
        </div>
      </div>
    </div>
  );
}